//
//  ViewController.m
//  Concentration
//
//  Created by Alessi Patrick on 9/14/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#define UIAlertViewTag_NextLevel 0x2

#import "CardViewController.h"
#import "GameControllerViewController.h"


static int cardRowCol[3][2] = {{4,4},{4,6},{6,6}};
static int cardOffset[3][2] = {{60,60},{10,70},{10,10}};
static int cardSize[3][2] = {{40,60},{40,60},{40,60}};

#define MAX_LEVEL 3


@implementation CardViewController
@synthesize cardViews;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    currentLevel = 0;
    self.cardViews = [[NSMutableArray alloc]initWithCapacity:36]; 

	// Do any additional setup after loading the view, typically from a nib.
    [self createCards];
    self.view.backgroundColor = [UIColor blackColor];
    
    showScore = [[UILabel alloc] initWithFrame:CGRectMake(100, 5, 200, 20)];
    showScore.backgroundColor = [UIColor clearColor];
    showScore.textColor = [UIColor whiteColor];
    showScore.textAlignment = UITextAlignmentRight;
    [self.view addSubview:showScore];
    showScore.text = [NSString stringWithFormat:@"我的墨水： %d", [[GameControllerViewController sharedGameControllerInstance] GetUserGold]];
    
    clickNumber = 0;
    firstTappedView = nil;
    isAnimating = NO;    
}
-(void) createCards
{
    // 16 * 4 cards
    // Create cards
    NSMutableArray *cards = [[NSMutableArray alloc] initWithCapacity:cardRowCol[currentLevel][0]*cardRowCol[currentLevel][1]];
    
    for (int i=1; i<=2; i++) {
        for (int j=1; j<=cardRowCol[currentLevel][0]*cardRowCol[currentLevel][1]/2; j++) {
            [cards addObject:[NSNumber numberWithInt:j]];
        }
    }
    
    // Shuffle cards
    srandom( time( NULL ) );
    int swapA, swapB;
    
    for (int i=0; i<100000; i++) {
        
        swapA = (random() % cardRowCol[currentLevel][0]*cardRowCol[currentLevel][1]);
        swapB = (random() % cardRowCol[currentLevel][0]*cardRowCol[currentLevel][1]);
        
        NSNumber *tempNumber = [cards objectAtIndex:swapA];
        [cards replaceObjectAtIndex:swapA 
                         withObject:[cards objectAtIndex:swapB]];
        [cards replaceObjectAtIndex:swapB
                         withObject:tempNumber];
    }
    
    [self addCardsToView:cards];
    
}

-(void) addCardsToView:(NSMutableArray*) cards
{
    
    CardImageView* card;
    CGRect cardFrame;
    CGRect cardOrigin = CGRectMake(0,0, cardSize[currentLevel][0], cardSize[currentLevel][1]);
    
    cardFrame.size = CGSizeMake(cardSize[currentLevel][0], cardSize[currentLevel][1]);
    CGPoint origin;
    int cardIndex = 0;
    
    NSTimeInterval timeDelay = 0.0;
    
    for (int i=0; i<cardRowCol[currentLevel][0]; i++) {
        for (int j=0; j<cardRowCol[currentLevel][1]; j++) {
            origin.y = i*70 + cardOffset[currentLevel][1];
            origin.x = j * 50 + cardOffset[currentLevel][0];
            cardFrame.origin = origin;
            
            // Create the card at the origin
            card = [[CardImageView alloc] initWithFrame:cardOrigin 
                                                  value:[[cards objectAtIndex:cardIndex] intValue]];
            
            // Configure gesture recognizer
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] 
                                           initWithTarget:self 
                                           action:@selector(handletap:)];
            tap.numberOfTapsRequired = 1;
            
            [card addGestureRecognizer:tap];
            
            
            [self.view addSubview:card];
            [self.cardViews addObject:card];
            // Animate moving the cards into position
            // In iOS 4 and later, use the Block-based animation methods.
            [UIView animateWithDuration:0.3 
                                  delay:timeDelay 
                                options:UIViewAnimationOptionCurveLinear 
                             animations: ^{
                                 card.frame = cardFrame;
                             } 
                             completion:NULL];
            
            timeDelay += 0.08;
            cardIndex++;
        }
        
    }
}


- (void)handletap:(UIGestureRecognizer *)gestureRecognizer
{
    
    // If an animation is running, ignore taps
    if (isAnimating)
        return;
    ++clickNumber;
    
    CardImageView *tappedCard = (CardImageView*) gestureRecognizer.view;
    
    // Has a card already been tapped?
    if (firstTappedView == nil)
    {
        // Flip the tapped card
        [UIView transitionWithView:tappedCard
                          duration:0.3
                           options:UIViewAnimationOptionTransitionFlipFromLeft
                        animations:^{ 
                            [tappedCard flipCard];
                        }
         
                        completion:NULL];
        // This is the first card, so just set it
        firstTappedView = tappedCard;
    }
    else if (firstTappedView != tappedCard)
    {
        // If the player didn't tap the same card again...
        
        // Ignore taps because we are animating
        isAnimating = YES;
        
        [UIView transitionWithView:tappedCard
                          duration:0.3
                           options:UIViewAnimationOptionTransitionFlipFromLeft
                        animations:^{ 
                            [tappedCard flipCard];
                        }
         
                        completion:NULL];
        // A card has already been tapped, so test for a match
        if (firstTappedView.value == tappedCard.value)
        {
            
            [self.cardViews removeObject:firstTappedView];
            [self.cardViews removeObject:tappedCard];
            // Player found a match
            // Remove the cards
            [UIView animateWithDuration:1 delay:1
                                options:UIViewAnimationOptionTransitionNone
                             animations:^{
                                 firstTappedView.alpha = 0; 
                                 tappedCard.alpha=0;
                             }
                             completion:^(BOOL finished) { 
                                 [firstTappedView removeFromSuperview];
                                 [tappedCard removeFromSuperview];
                                 
                                 [self checkStatus];
                                 // Stop ignoring taps because animation is done
                                 isAnimating=NO;
                             }
             ];
            
            
            // Reset the first tapped card to nil
            firstTappedView = nil;
        }
        
        else
        {
            // Flip both cards back over
            secondTappedView = tappedCard;
            [self performSelector:@selector(flipCards) withObject:nil
                       afterDelay:0.6];
            
        }
    }
}

-(void) flipCards
{
    [UIView transitionWithView:firstTappedView
                      duration:0.6
                       options:UIViewAnimationOptionTransitionFlipFromRight
                    animations:^{ 
                        [firstTappedView flipCard];
                    }
                    completion:NULL
     ];
    [UIView transitionWithView:secondTappedView
                      duration:0.6
                       options:UIViewAnimationOptionTransitionFlipFromRight
                    animations:^{ 
                        [secondTappedView flipCard];
                    }
                    completion:^(BOOL finished) { 
                        // Stop ignoring events because animation is done
                        isAnimating=NO;
                        
                    }
     ];
    
    // Reset the first tapped cards to nil
    firstTappedView = nil;
    secondTappedView = nil;
}

-(void)checkStatus
{
    if([self.cardViews count] != 0)
    {
        return;
    }
    else
    {
        int userGetGold = 0;
        switch (currentLevel)
        {
            case 0:
                userGetGold = MAX_Level1Gold - clickNumber;
                break;
            case 1:
                userGetGold = MAX_Level2Gold - clickNumber;
                break;
            case 2:
                userGetGold = MAX_Level3Gold - clickNumber;
                break;
            default:
                userGetGold = 0;
                break;
        }

        [[GameControllerViewController sharedGameControllerInstance] SetUserGold:userGetGold+[[GameControllerViewController sharedGameControllerInstance] GetUserGold]];
        showScore.text = [NSString stringWithFormat:@"我的墨水： %d", [[GameControllerViewController sharedGameControllerInstance] GetUserGold]];
        
        if(currentLevel ==2)
        {
            //game finish 3 level
            UIAlertView * al = [[UIAlertView alloc] initWithTitle:@"恭喜过关" message:[NSString stringWithFormat:@"您获得%d点墨水奖励！", userGetGold] delegate:self cancelButtonTitle:nil otherButtonTitles:@"返回主菜单", nil];
            al.tag = UIAlertViewTag_NextLevel;
            [al show];
        }
        else
        {
            UIAlertView * al = [[UIAlertView alloc] initWithTitle:@"恭喜过关" message:[NSString stringWithFormat:@"您获得%d点墨水奖励！", userGetGold] delegate:self cancelButtonTitle:nil otherButtonTitles:@"主菜单",@"下一关", nil];
            al.tag = UIAlertViewTag_NextLevel;
            [al show];
            
            
        }
    }
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == UIAlertViewTag_NextLevel)
    {
        if(buttonIndex == 0)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else if(buttonIndex == 1)
        {
            currentLevel++;
            [self createCards];
        }
    }
}

// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
- (void)alertViewCancel:(UIAlertView *)alertView
{
    
}

@end
